package com.hikvision.ae.service.impl;

import com.alibaba.fastjson.JSON;
import com.hikvision.ae.common.AreaInfo;
import com.hikvision.ae.common.Gps;
import com.hikvision.ae.common.MassPoint;
import com.hikvision.ae.common.PythonExecutor;
import com.hikvision.ae.service.BaseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author jinjinhui
 * @date 2020/5/14
 */
@Service
@Slf4j
public class BaseServiceImpl implements BaseService {

    @Value("${python.algorithm.getGpsPointsFromExcel}")
    private String getGpsPointsFromExcel;
    @Value("${python.algorithm.getGpsLinesFromJsonFile}")
    private String getGpsLinesFromJsonFile;

    //坐标点文件路径
    private String jsonFilePath;
    //误报范围文件路径
    private String areaFilePath;

    private final String tempPath = System.getProperty("user.dir") + File.separator + "temp" + File.separator;

    @Override
    public List<MassPoint> getPointsFromFile(MultipartFile multipartFile) {
        //将文件保存到临时文件夹

        File path = new File(tempPath);
        if(!path.exists()){
            path.mkdirs();
        }
        String fileName = multipartFile.getOriginalFilename();
        File file = new File(tempPath + fileName);
        try {
            multipartFile.transferTo(file);
            //利用python方法解析
            String gpsPoints = PythonExecutor.executeForString(getGpsPointsFromExcel, tempPath + fileName);
            List<Gps> gpsList = JSON.parseArray(gpsPoints, Gps.class);
            if(fileName.contains("废弃")){
                //废弃斑马线的位置需要保存下来
                File jsonFile = new File(tempPath + fileName.substring(0, fileName.lastIndexOf("."))+".json");
                FileWriter writer = new FileWriter(jsonFile);
                writer.write(JSON.toJSONString(gpsList));
                writer.flush();
                writer.close();
                jsonFilePath = jsonFile.getAbsolutePath();
                log.info("写入{}成功, jsonFilePath = {}", jsonFile.getName(), jsonFilePath);
            }
            List<MassPoint> points = gpsList.stream().map(gps->{
                MassPoint point = new MassPoint();
                point.setName(gps.getBusSelfId());
                point.setId(gps.getAlarmId());
                point.setStyle(fileName.contains("废弃")?0:1);
                point.setLnglat(Arrays.asList(gps.getLongitude(), gps.getLatitude()));
                return point;
            }).collect(Collectors.toList());
            return points;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public List<AreaInfo> analysis(Integer errorRange) {
        log.info("jsonFilePath = {}", jsonFilePath);
        if(StringUtils.isEmpty(jsonFilePath)){
            return null;
        }
        try {
            String lines =  PythonExecutor.executeForString(getGpsLinesFromJsonFile, jsonFilePath, errorRange.toString());
            String fileName = "废弃斑马线误报区域.json";
            File areaFile = new File(tempPath + fileName);
            areaFile.deleteOnExit();
            FileWriter writer = new FileWriter(areaFile);
            writer.write(lines);
            writer.flush();
            writer.close();
            areaFilePath = areaFile.getAbsolutePath();

            List<AreaInfo> linesArray = JSON.parseArray(lines, AreaInfo.class);
            return linesArray;

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public boolean isAnalysised() {
        return !StringUtils.isEmpty(areaFilePath);
    }

    @Override
    public File exportAlarmRange() {
        if(StringUtils.isEmpty(areaFilePath)){
            return null;
        }
        File jsonFile = new File(areaFilePath);
        return jsonFile;
    }
}
